package com.thprojects.myphotomemories.view;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.controller.WebController;
import com.thprojects.myphotomemories.model.LoggedUser;
import com.thprojects.myphotomemories.model.WebPhoto;
import com.thprojects.myphotomemories.view.components.WebPhotoAdapter;

import exception.NotOnlineException;

public class WebPhotosView extends Activity {

	List<WebPhoto> mPhotos;
	ProgressDialog mProgressDialog;
	GridView mPhotoGrid;
	Button mMore, mMy;
	LoggedUser mLoggedUser;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_photos_view);
		
		mLoggedUser = LoggedUser.getLoggedUser();
		if (mLoggedUser == null){
			GuiController.showError(this, "You must be logged to see web photos");
			finish();
		}
		
		mPhotoGrid = (GridView)findViewById(R.id.web_photos_grid);
		mMore = (Button)findViewById(R.id.web_more_photos);
		mMy = (Button)findViewById(R.id.web_my_photos);
		
		GetPhotosTask gpt = new GetPhotosTask();
		gpt.execute();
		
	}
	
	private class GetPhotosTask extends AsyncTask<Void, Void, Void>{	
		@Override
		protected Void doInBackground(Void... v) {			
			try {
				mPhotos = WebController.getPhotos(WebPhotosView.this, mLoggedUser.getName(), mLoggedUser.getPassword());		
			} catch (NotOnlineException e) {
				mPhotos = null;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void v) {
			super.onPostExecute(v);
			mProgressDialog.cancel();
			if (mPhotos == null){
				GuiController.showError(WebPhotosView.this, "You must be conntected to Internet to see web photos");
				return;
			}
			
			mPhotoGrid.setAdapter(new WebPhotoAdapter(WebPhotosView.this, mPhotos));

			mPhotoGrid.setOnItemClickListener(new OnItemClickListener() {
		        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		            Toast.makeText(WebPhotosView.this, "" + position, Toast.LENGTH_SHORT).show();
		        }
		    });
			
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = ProgressDialog.show(WebPhotosView.this, "Downloading", "Getting images. Please wait...");
		}
	}
}
